package com.server.orm.db;

import com.alibaba.fastjson.JSON;
import org.hibernate.Session;
import com.server.orm.HibernateManager;
import com.server.util.LogUtil;

import java.lang.reflect.InvocationTargetException;

public class TableLongKeyBase {

    private Long K;
    private String V = "{}";
    private Object data = null;

    private void setK(Long K) {
        this.K = K;
    }

    private Long getK() {
        return K;
    }

    private void setV(String V) {
        this.V = V;
    }

    private String getV() {
        return V;
    }

    public void saveOrUpdate() {
        Session session = HibernateManager.getSession();
        if (null != this.data) {
            this.V = JSON.toJSONString(this.data, true);//默认忽略值为null的属性
        }
        session.merge(K.toString(), this);
    }

    public void saveOrUpdate(long key) {
        Session session = HibernateManager.getSession();
        this.K = key;
        if (null != this.data) {
            this.V = JSON.toJSONString(this.data, true);//默认忽略值为null的属性
        }
        session.merge(String.valueOf(key), this);
    }

    protected static <T> T get(Class<T> c, long key) {
        Session session = HibernateManager.getSession();
        return session.get(c, key);
    }

    public static long insert(long key, TableLongKeyBase o) {
        Session session = HibernateManager.getSession();
        o.setK(key);
        if (null != o.data) {
            o.setV(JSON.toJSONString(o.data, true));//默认忽略值为null的属性
        }
        session.persist(String.valueOf(key), o);
        return o.getK();
    }

    public static long insert(TableLongKeyBase o) {
        Session session = HibernateManager.getSession();
        if (null != o.data) {
            o.setV(JSON.toJSONString(o.data, true));//默认忽略值为null的属性
        }
        session.persist(o);
        return o.getK();
    }

    public static void delete(String s) {
        Session session = HibernateManager.getSession();
        session.remove(s);
    }

    protected final <T> T Data(Class<T> c) {
        if (null != data) {
            return (T) data;
        }
        if (null != V && !V.trim().isEmpty() && !V.trim().equals("{}")) {
            data = JSON.parseObject(V, c);
        } else {
            try {
                data = c.getDeclaredConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                LogUtil.game.error("Exception", e);
            }
        }
        return (T) data;
    }
}
